package com.hongdezhi.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

	private String excludedPages;       
	private String[] excludedPageArray; 
	FilterConfig fConfig;
	public void init(FilterConfig filterConfig) throws ServletException {
		fConfig=filterConfig;
		excludedPages = fConfig.getInitParameter("excludedPages");   
		
		if (excludedPages!=null) {     
		excludedPageArray = excludedPages.split(",");     
		}     
		     
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		boolean isExcludedPage = false;
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		for (String page : excludedPageArray) {//判断是否在过滤url之外     
		if(req.getServletPath().equals(page)){     
		isExcludedPage = true;     
		break;     
		}     
		}     
		  
		if (isExcludedPage) {//在过滤url之外     
		chain.doFilter(req, resp);     
		} else {//不在过滤url之外，判断session是否存在     
		HttpSession session = req.getSession();     
		if (session == null || session.getAttribute("user") == null) {     
		resp.sendRedirect(req.getContextPath()+"/login.jsp");     
		} else {     
		chain.doFilter(req, resp);     
		}     
		}   
	
	}
	public void destroy() {
	}

}
